import { createRouter, createWebHistory } from 'vue-router';
import UserCenter from '@/views/UserCenter.vue';
import Login from '@/views/Login.vue';
import axios from 'axios'; // 用于校验Token有效性（可选）
import Dashboard from '@/views/Dashboard.vue';

const routes = [
  { path: '/login', component: Login },
  { path: '/',component: Dashboard},
  { path: '/Dashboard',component: Dashboard},
  {
    path: '/user',
    component: UserCenter,
    meta: { requiresAuth: true } // 标记需要登录授权
  },
  { path: '/:pathMatch(.*)*', redirect: '/login' } // 404页面重定向到登录页
];

const router = createRouter({
  history: createWebHistory(),
  routes
});
console.log('路由表:', router.getRoutes()); // 打印所有路由

// 路由守卫：校验登录状态和Token有效性
router.beforeEach(async (to, from, next) => {
  if (to.meta.requiresAuth) {
    // 1. 获取本地存储的Token
    const token = localStorage.getItem('token');

    // 2. 无Token → 未登录，跳转到登录页
    if (!token) {
      next('/login');
      return;
    }

    // 3. 有Token → 校验Token有效性（可选，增强安全性）
    try {
      // 向后端发送Token校验请求（需后端配合实现校验接口）
      await axios.get('/api/user/verify-token', {
        headers: { Authorization: `Bearer ${token}` }
      });
      // Token有效 → 放行
      next();
    } catch (error) {
      // Token无效/过期 → 清除Token并跳转登录页
      localStorage.removeItem('token');
      next('/login');
    }
  } else {
    // 不需要授权的页面直接放行
    next();
  }
});

export default router;